var installPage = 'https://chrome.google.com/webstore/detail/hkiedadobebfhcolfkkjedcbihkjonol';


if (!document.location.href.match(/flickr.com\/groups\/[^\/]+\/discuss\/\d+/)) {
	exit (1);
}

var backgroundPort = chrome.extension.connect({name: "flickrinlineeditlight"});
backgroundPort.onMessage.addListener(function (msg) {
        if (!msg.success) {
                GM_log("ERROR: " + msg.statusText);
        }
	if (msg.name == 'getVersion') {
	        $(msg.callbackId).fireEvent(msg.callbackEvent, msg.version);
	}
});

function getVersion(callbackId, callbackEvent) {
        try {
                backgroundPort.postMessage({ name: 'getVersion', callbackEvent: callbackEvent, callbackId: callbackId });
        } catch(e) {
                GM_log("ERROR connecting to the background page: " + e);
        }
}

// version check
	new Element('span', {
		id: 'FIEL-updatenotifier',
		styles: {
			display: 'none',
			visibility: 'hidden'
		},
		events: {
			'checkversion': function (evt) {
				try {
					GM_setValue("FIEL.version", evt);
					checkVersion(evt);
				} catch (e) {
				}
			}
		}
	}).inject($$('body')[0], 'bottom');
	getVersion('FIEL-updatenotifier', 'checkversion');

function showUpdateNotification(data) {
	var onlineVersion = data.onlineVersion;
	var version = data.version;
	var beta = data.beta;

    var color = 'white';
	var updatespan = $('AlesaDams_updates_span');
	if (!$chk(updatespan)) {
	    updatespan = new Element('span', {
		id: 'AlesaDams_updates_span',
		// copied from Google++ userscript:
		styles: {
		    'background': '#E0E0E0',
		    padding: '2px 4px',
		    display: 'block',
		    '-moz-background-clip': 'border',
		    '-moz-background-origin': 'padding',
		    '-moz-background-inline-policy': 'continuous',
		    position: 'fixed',
		    opacity: '0.7',
		    'z-index': 1011, // the lightbox layer is 1004 on the new photo page
		    bottom: '5px',
		    right: '5px',
		    left: '5px'
		}
	    }).inject($(document).getElement("body"));
	} else {
		// make it darker if already created by another script:
		updatespan.setStyle('background', '#E0E0E0');
	}
    var bgColor = beta ? 'grey' : 'black';
	var updater = new Element('span', {
		styles: {
			background: bgColor + ' none repeat scroll 0% 0%',
			margin: '2px 5px',
			position: 'relative',
			'float': beta ? 'left' : 'right',
			opacity: beta ? '0.5' : ''
		}
	}).inject(updatespan);
    new Element('a', {
        html: 'Flickr Inline Edit Light: ' + (beta ? 'beta ' + version : onlineVersion + ' available'),
        href: installPage,
        target: '_blank',
        title:  'to the ' + (beta ? 'stable version' : '') + ' install page (opens in new tab)',
        styles: {
            'color': color,
            'text-decoration': 'none'
        }
    }).inject(updater);
    new Element('a', {
        html: beta ? ' (feedback)' : ' (Changes)',
        title: 'opens in new tab',
        href: 'http://www.flickr.com/groups/flickrhacks/discuss/72157635091449571/',
        styles: {
            'text-decoration': 'none'
        },
        target: '_blank'
    }).inject(updater);
}

function outOfDate(version, onlineVersion) {
        var reVersionMatch      = /(\d+)\.(\d+)\.(\d+)/;
        var onlineVersionParts  = reVersionMatch.exec(onlineVersion);
        var currentVersionParts = reVersionMatch.exec(version);
        var onlineVersionMajor, onlineVersionMinor, onlineVersionBuild;
        //[ onlineVersion, onlineVersionMajor, onlineVersionMinor, onlineVersionBuild ] = onlineVersionParts; 'invalid left-hand side' in Chrome
        onlineVersionMajor = onlineVersionParts[1];
        onlineVersionMinor = onlineVersionParts[2];
        onlineVersionBuild = onlineVersionParts[3];
        var currentVersionMajor, currentVersionMinor, currentVersionBuild;
        //[ currentVersion, currentVersionMajor, currentVersionMinor, currentVersionBuild] = currentVersionParts;
        currentVersionMajor = currentVersionParts[1];
        currentVersionMinor = currentVersionParts[2];
        currentVersionBuild = currentVersionParts[3];
        // first check major: important update! => rewrite, flickr updates, greasemonkey updates
        if (parseInt(onlineVersionMajor, 10) > parseInt(currentVersionMajor, 10)) {
            return true;
        } else if (parseInt(onlineVersionMajor, 10) === parseInt(currentVersionMajor, 10)) { // we don't want to downgrade
            // minor version update => new functionality
            if (parseInt(onlineVersionMinor, 10) > parseInt(currentVersionMinor, 10)) {
                return true;
            } else if (parseInt(onlineVersionMinor, 10) === parseInt(currentVersionMinor, 10)) { // we don't want to downgrade
                // build version update => bugfixes
                if (parseInt(onlineVersionBuild, 10) > parseInt(currentVersionBuild, 10)) {
                    return true;
                }
            }
        }
	return false;
}

function getThreadReply(data) {
        var threadId = data.threadId;
	var replyId = data.replyId;
        var callback = data.callback;

        try {  
                new Request({
                        url: 'http://www.flickr.com',
                        onSuccess: function (responseText, responseXML) {
                                    try {
                                        var result;
                                        try {
                                            result = JSON.parse(responseText);
                                        } catch (e) {
                    				GM_log("error parsing JSON reply for thread " + threadId + " (" + e + "): '" + responseText);
		    				callback({ threadId: threadId, success: false, message: e });
						return;
                                        }
                                        if (result.stat === 'fail') {
                                                callback({ threadId: threadId, success: false, message: result.message });
                                        } else {
                                                callback({ threadId: threadId, success: true, message: result.reply.message._content });
                                        }
                                    } catch (e) {
                                        GM_log("ERROR processing result: " + e);
                                        callback({ threadId: threadId, success: false, message: "ERROR processing result: " + e });
                                    }
                                },
                                onFailure: function (response) {
                                        GM_log("error: " + response.statusText);
                                        callback({ threadId: threadId, success: false, message: response.statusText });
                                }
                }).get('/services/rest', {
                        api_key: GM_getMagisterLudi(),
                        auth_hash: GM_getAuthHash(),
                        auth_token: GM_getAuthToken(),
                        format: 'json',
                        method: 'flickr.groups.discuss.replies.getInfo',
                        nojsoncallback: 1,
                        topic_id: threadId,
			reply_id: replyId
                });
        } catch (e) {
                callback({ threadId: threadId, success: false, message: 'Exception: ' + e });
        }
}

function checkVersion(version) {
    var lastVersionCheckTime = GM_getValue("lastVersionCheckTime");
    var elapsedtime;
    var CPStartTime = new Date();
    if ($chk(lastVersionCheckTime)) {
        elapsedtime = CPStartTime.getTime() - lastVersionCheckTime;
    }
    if (!$chk(lastVersionCheckTime) || elapsedtime / 1000 > 60 * 60 * 12) { //more then 12h ago
    	getThreadReply({ threadId: '72157634086550096',
			 replyId: '72157635090723013',
			callback: function(retval) {
				var success = retval.success;
				var message = retval.message;
				if (!success) {
					GM_log("error getting version info: " + message);
					GM_deleteValue("onlineVersion");
					GM_deleteValue("lastVersionCheckTime");
					return;
				}
				var onlineVersion = message.split(/<i>current version:\s*/)[1].split(/<\/i>/)[0];
				GM_setValue("onlineVersion", onlineVersion);
				GM_setValue("lastVersionCheckTime", (new Date()).getTime().toString());
			}
	});
        GM_setValue("lastVersionCheckTime", CPStartTime.getTime().toString());
    }

    var onlineVersion = GM_getValue("onlineVersion");
    if ($chk(onlineVersion)) {
        var updateAvailable = outOfDate(version, onlineVersion);
        if (updateAvailable) {
        	showUpdateNotification({ onlineVersion: onlineVersion });
        } else if (version != onlineVersion) {
		showUpdateNotification({ version: version, beta: true });
	}
    }
}

function showAreYouSureDialog(topicID, commentID, callback) {
	var ret = confirm("Are you sure you want to remove this reply?");
	callback({ answer: ret ? "yes" : "no", topicID: topicID, commentID: commentID });
}

function removeComment(topicID, commentID, callback) {
	GM_log("DEBUG: removing comment '" + commentID + "' from topic '" + topicID + "'");
        try {  
                new Request({
                        url: 'http://www.flickr.com',
                        onSuccess: function (responseText, responseXML) {
                                    try {
                                        var result;
                                        try {
                                            result = JSON.parse(responseText);
                                        } catch (e) {
                    				GM_log("error parsing JSON reply for thread " + topicID + " (" + e + "): '" + responseText);
		    				callback({ topicID: topicID, commentID: commentID, success: false, message: e });
						return;
                                        }
                                        if (result.stat === 'fail') {
						if (result.code != 3) { // insufficient permissions - not really though
	                                                callback({ topicID: topicID, commentID: commentID, success: false, message: result.message });
							return;
						}
						removeCommentWithPOST(topicID, commentID, callback);
                                        } else {
                                                callback({ topicID: topicID, commentID: commentID, success: true });
                                        }
                                    } catch (e) {
                                        GM_log("ERROR processing result: " + e);
                                        callback({ topicID: topicID, commentID: commentID, success: false, message: "ERROR processing result: " + e });
                                    }
                                },
                                onFailure: function (response) {
                                        GM_log("error: " + response.statusText);
                                        callback({ topicID: topicID, commentID: commentID, success: false, message: response.statusText });
                                }
                }).get('/services/rest', {
                        api_key: GM_getMagisterLudi(),
                        auth_hash: GM_getAuthHash(),
                        auth_token: GM_getAuthToken(),
                        format: 'json',
                        method: 'flickr.groups.discuss.replies.delete',
                        nojsoncallback: 1,
                        topic_id: topicID,
			reply_id: commentID
                });
        } catch (e) {
                callback({ topicID: topicID, commentID: commentID, success: false, message: 'Exception: ' + e });
        }
}

function removeCommentWithPOST(topicID, commentID, callback) {
	GM_log("DEBUG: removing comment '" + commentID + "' from topic '" + topicID + " (POST)");
	var baseUrl = /(^.*flickr\.com\/groups\/[^\/]+\/discuss)/.exec(document.location.href)[1];
        try {  
                new Request({
                        url: baseUrl + '/' + topicID + '/' + commentID + '/delete',
			headers: {
				"Content-Type": "application/x-www-form-urlencoded"
			},	
                        onSuccess: function (responseText, responseXML) {
				var tempDiv = new Element('div');
				tempDiv.innerHTML = responseText.stripScripts();
				var problem = tempDiv.getElement('p.Problem');
				if ($chk(problem)) {
					callback({ topicID: topicID, commentID: commentID, success: false, message: problem.innerHTML });
				} else {
					callback({ topicID: topicID, commentID: commentID, success: true });
				}
                        },
                        onFailure: function (response) {
                                GM_log("error: " + response.statusText);
                                callback({ topicID: topicID, commentID: commentID, success: false, message: response.statusText });
                        }
                }).post({
			magic_cookie: GM_getAuthHash(),
			done: 1
		});
        } catch (e) {
                callback({ topicID: topicID, commentID: commentID, success: false, message: 'Exception: ' + e });
        }
}

var topicID = document.location.href.match(/flickr.com\/groups\/[^\/]+\/discuss\/(\d+)/)[1];
var groupName = document.location.href.match(/flickr.com\/groups\/([^\/]+)\/discuss\/\d+/)[1];
$$('table.TopicReply').forEach(function (table) {
	table.getElements('td.Said').forEach(function (entry) {
		var small = entry.getElements('small').forEach(function (smallEl) {
			var hasEdit = false;
			var hasDelete = false;
			var editLink = null;
			var deleteLink = null;
			var deleteHref = new RegExp(groupName + '\/discuss\/' + topicID + '\/\\d+\/delete');
			var editHref = new RegExp(groupName + '\/discuss\/' + topicID + '\/\\d+\/edit');
			smallEl.getElements('a').forEach(function (anchor) {
				var href = anchor.get('href');
				if (!$chk(href)) {
					return;
				}
				if (href.match(deleteHref)) {
					hasDelete = true;
					deleteLink = anchor;
					return;
				}
				if (href.match(editHref)) {
					hasEdit = true;
					editLink = anchor;
					return;
				}
			});
			if (!hasEdit || !hasDelete) {
				return;
			}
			var commentID = editLink.get('href').match(new RegExp(groupName + '\/discuss\/' + topicID + '\/(\\d+)\/edit'))[1];
			var separator = new Element('label', {
				html: ' | '
			}).inject(deleteLink, 'after');
/*
			var inlineEditLink = new Element('a', {
				html: 'inline edit',
				href: 'http://www.flickr.com/groups/' + groupName + '/discuss/' + topicID + '/' + commentID,
				events: {
					click: function(evt) {
						evt.preventDefault();
					}
				}
			}).inject(separator, 'after');
			separator = new Element('label', {
				html: ' | '
			}).inject(inlineEditLink, 'after');
*/
			var inlineDeleteLink = new Element('a', {
				html: 'inline delete',
				href: 'http://www.flickr.com/groups/' + groupName + '/discuss/' + topicID  + '/' + commentID,
				events: {
					click: function(evt) {
						evt.preventDefault();
						var target = $(evt.target);
						var previousError = $('FIEL-error-' + commentID);
						if ($chk(previousError)) previousError.destroy();
						var commentRow = target.getParent('td.Said').getParent('tr');
						commentRow.setStyle('opacity', 0.3);
						showAreYouSureDialog(topicID, commentID, function(deleteAnswer) {
							if (deleteAnswer.answer == 'no') {
								commentRow.setStyle('opacity', 1.0);
								return;
							}
							var content = commentRow.getElement('td.Said');
							// make an 'empty' copy
							var contentCopy = content.clone();
							contentCopy.empty();
							content.getChildren('h4').clone().inject(contentCopy);

							new Element('img', { title: 'removing', src: 'http://www.flickr.com/images/pulser2.gif' }).inject(contentCopy);
							contentCopy.replaces(content);
							removeComment(deleteAnswer.topicID, deleteAnswer.commentID, function (retval) {
								contentCopy.getChildren('img[src*=pulser]').dispose();
								if (retval.success) {
									new Element('i', { html: 'removed' }).inject(contentCopy);
									return;
								}
								commentRow.setStyle('opacity', 1.0);
								new Element('span', {
									id: 'FIEL-error-' + commentID,
									html: 'error deleting reply: ' + retval.message + " (click to restore)",
									styles: {
										color: 'red',
										'font-weight': 'bold',
										cursor: 'pointer'
									},
									events: {
										click: function(evt) {
											content.replaces(contentCopy);
											contentCopy.destroy();
										}
									}		
								}).inject(contentCopy);
							});
						});
					}
				}
			}).inject(separator, 'after');
		});
	});
});

